#coding=utf-8
from sdsource.web.utility import *
from sdsource.models import FuQuanRatio
from sdsource.exception import NoPriceError

from sdsource.web.sina.stock import get_ipo
import datetime

#取得复权因子的网址url
url_fuquan = 'http://money.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/%s.phtml?year=%s&jidu=%s'

def get_fqratios_from_soup(soup):
    '''返回[[日期, ratio], [日期, ratio] ...]'''
    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_fqratio_from_row(row):
        
        r = []
        tds = row.findAll('td')
        
        dt = tds[0].contents[0].string
        if not dt:dt = tds[0].contents[0].contents[1].string
        dt = dt.strip()
        
        dt = dt.encode('u8')
        r = float( get_s(tds[-1]) )
        return [dt, r]
           
    rs = []
    
    t = unicode('日期', 'u8')
    rq = soup.find(text = t)
    
    table = rq.parent.parent.parent.parent.parent
    trs = table.findAll('tr')
    if len(trs) <= 2 :return None
     
    trs = trs[2:]

    for tr in trs:
        r = get_fqratio_from_row(tr)
        rs.append(r)

    rs.reverse()
    
    return rs

def get_fqrs_by_jd(code, year, jd):
    
    u = url_fuquan%(code, year, jd)
    soup = get_soup(u)
    return get_fqratios_from_soup(soup)
    
def get_fqr_on(code, tdate):
    '''取得某一股票某一天的复权因子'''
    
    year, month, day = map(int, tdate.split('-'))
    jd = get_jd(month)
    rs = get_fqrs_by_jd(code, year, jd)
    
    if not rs:
        raise NoPriceError(code, tdate)
        
    for r in rs:
        if r[0] == tdate:
            return r
    
    raise NoPriceError(code, tdate)

def get_fqrs_between(code, start, end=None):
    
    if not end:
        end = datetime.date.today().isoformat()
        
    rss = []
    
    sy, sm, sd = map(int, start.split('-'))
    ey, em, ed = map(int, end.split('-'))
    
    yjs = get_yjs(sy, get_jd(sm), ey, get_jd(em) )  
    
    for yj in yjs:
        y,j = yj
        
        rs = get_fqrs_by_jd(code, y, j)
        if rs:rss.extend(rs)
    
    #for p in pss:print p.date
           
    s = 0; e = 0
    for r in rss:
        if r[0] >= start:
            s = rss.index(r)
            break
          
    for r in rss:        
        if r[0] == end:
            e = rss.index(r) + 1
            break
            
        if r[0] > end:
            e = r[0].index(r)
            break
            
    if e == 0:
        rss = rss[s:]
    else:        
        rss = rss[s:e]
    
    fqrs = []
    #去除重复
    ratio = -1
    for r in rss:
        #print r[1], ratio
        if r[1] != ratio:
            fqrs.append(r)
            ratio = r[1]
    return fqrs 

def get_fqrs(code, ipo=None):

    if not ipo: ipo = get_ipo(code)
    rs = get_fqrs_between(code, ipo)
    
    fqr = FuQuanRatio(code)
    for r in rs:
        fqr.append_fqr(r[0], r[1])
    
    return fqr
    
           
